<template>
  <div class="page-wrapper">
    <div class="login-container">
      <!-- 左侧 -->
      <div class="left-section">
        <div class="left-content">
          <h1 class="overlay-title">东软智慧社区</h1>
          <p class="overlay-subtitle">智能生活 从这里开始</p>
          <div class="decoration-circle"></div>
        </div>
      </div>
      
      <!-- 右侧 -->
      <div class="right-section">
        <div class="form-wrapper">
          <div class="form-header">
            <h2 class="welcome-text">{{ isLogin ? '欢迎登录' : '创建账号' }}</h2>
            <p class="welcome-subtitle">{{ isLogin ? '使用您的账号进入系统' : '加入我们的智慧社区' }}</p>
          </div>

          <!-- 登录表单 -->
          <el-form v-if="isLogin" :model="loginForm" ref="loginFormRef" :rules="loginRules" label-position="top">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="loginForm.username" 
                placeholder="请输入用户名"
                prefix-icon="User"
                class="input-style"
                size="large"
                clearable
              />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                class="input-style"
                show-password
                size="large"
                clearable
              />
            </el-form-item>
            <div class="form-options">
              <el-checkbox v-model="rememberMe" class="custom-checkbox">记住我</el-checkbox>
              <el-link type="primary" @click="showForgotPasswordDialog">忘记密码？</el-link>
            </div>
            <el-button 
              type="primary" 
              @click="handleLogin" 
              class="custom-login-button"
              :loading="loading"
              :disabled="loading"
              size="large"
            >
              {{ loading ? '登录中...' : '立即登录' }}
            </el-button>
            <el-button 
              type="info" 
              @click="handleVisitorLogin" 
              class="visitor-login-button"
              size="large"
              plain
            >
              访客登记
            </el-button>
            <div class="register-tip">
              还没有账号？<el-link type="primary" @click="toggleForm">立即注册</el-link>
            </div>
          </el-form>

          <!-- 注册表单 -->
          <el-form v-if="!isLogin" :model="registerForm" ref="registerFormRef" :rules="registerRules" label-position="top">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" class="input-style" size="large" clearable />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password class="input-style" size="large" clearable />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" prefix-icon="Lock" show-password class="input-style" size="large" clearable />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" prefix-icon="Message" class="input-style" size="large" clearable />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号码" prefix-icon="Phone" class="input-style" size="large" clearable />
            </el-form-item>
            <el-button 
              type="primary" 
              class="custom-login-button" 
              :loading="loading"
              :disabled="loading"
              @click="handleRegister"
              size="large"
            >
              {{ loading ? '注册中...' : '立即注册' }}
            </el-button>
            <div class="register-tip">
              已有账号？<el-link type="primary" @click="toggleForm">返回登录</el-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordDialogVisible"
      title="重置密码"
      width="30%"
      center
      class="custom-dialog"
    >
      <el-form :model="forgotPasswordForm" :rules="forgotPasswordRules" ref="forgotPasswordFormRef" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="forgotPasswordForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="forgotPasswordForm.email" placeholder="请输入您的邮箱" clearable />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="forgotPasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="forgotPasswordDialogVisible = false" round>取消</el-button>
          <el-button type="primary" @click="handleForgotPassword" :loading="forgotLoading" round>
            {{ forgotLoading ? '提交中...' : '提交' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, register, forgotPassword } from '../api/api'

const router = useRouter()
const isLogin = ref(true)
const loading = ref(false)
const forgotLoading = ref(false)
const forgotPasswordDialogVisible = ref(false)

const loginForm = reactive({ username: '', password: '', remember: false })
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const forgotPasswordFormRef = ref(null)
const rememberMe = ref(false)

const forgotPasswordForm = reactive({ username: '', email: '', newPassword: '' })
const registerForm = reactive({ username: '', password: '', confirmPassword: '', email: '', phone: '' })

const forgotPasswordRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
})

const loginRules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
  ]
})

const validatePass2 = (rule, value, callback) => {
  if (value !== registerForm.password) callback(new Error('两次输入密码不一致!'))
  else callback()
}

const registerRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

onMounted(() => {
  const savedUsername = localStorage.getItem('savedUsername')
  const savedPassword = localStorage.getItem('savedPassword')
  if (savedUsername && savedPassword) {
    loginForm.username = savedUsername
    loginForm.password = savedPassword
    rememberMe.value = true
  }
})

const handleLogin = async () => {
  loginFormRef.value?.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await login({ username: loginForm.username, password: loginForm.password })
      if (res.code === 200 && res.data) {
        if (rememberMe.value) {
          localStorage.setItem('savedUsername', loginForm.username)
          localStorage.setItem('savedPassword', loginForm.password)
        } else {
          localStorage.removeItem('savedUsername')
          localStorage.removeItem('savedPassword')
        }
        const userData = res.data.user
        localStorage.setItem('userId', userData.userId)
        localStorage.setItem('role', userData.role)
        localStorage.setItem('cartId', res.data.cartId)
        localStorage.setItem('userInfo', JSON.stringify({
          userId: userData.userId,
          username: userData.username,
          role: userData.role,
          email: userData.email,
          phoneNumber: userData.phoneNumber
        }))
        ElMessage.success('登录成功')
        await router.push(userData.role === 'admin' ? '/admin/dashboard' : '/main/dashboard')
      } else ElMessage.error(res.message || '登录失败')
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '登录失败')
    } finally {
      loading.value = false
    }
  })
}

const toggleForm = () => {
  isLogin.value = !isLogin.value
  loading.value = false
  isLogin.value ? loginFormRef.value?.resetFields() : registerFormRef.value?.resetFields()
  if (!isLogin.value) Object.keys(registerForm).forEach(key => registerForm[key] = '')
}

const handleRegister = async () => {
  registerFormRef.value?.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await register({
        username: registerForm.username,
        password: registerForm.password,
        email: registerForm.email,
        phone: registerForm.phone
      })
      if (res.code === 200) {
        ElMessage.success('注册成功')
        isLogin.value = true
        loginForm.username = registerForm.username
      } else ElMessage.error(res.message || '注册失败')
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '注册失败')
    } finally {
      loading.value = false
    }
  })
}

const showForgotPasswordDialog = () => {
  forgotPasswordDialogVisible.value = true
  forgotPasswordFormRef.value?.resetFields()
}

const handleForgotPassword = async () => {
  forgotPasswordFormRef.value?.validate(async (valid) => {
    if (!valid) return
    forgotLoading.value = true
    try {
      const res = await forgotPassword({
        username: forgotPasswordForm.username,
        email: forgotPasswordForm.email,
        newPasswordHash: forgotPasswordForm.newPassword
      })
      if (res.code === 200) {
        ElMessage.success('密码重置成功')
        forgotPasswordDialogVisible.value = false
        forgotPasswordFormRef.value?.resetFields()
      } else ElMessage.error(res.message || '密码重置失败')
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '密码重置失败')
    } finally {
      forgotLoading.value = false
    }
  })
}

const handleVisitorLogin = () => router.push('/visitor-register')
</script>

<style scoped>
.page-wrapper {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 2rem;
}

.login-container {
  display: flex;
  width: 960px;
  height: 600px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  background: white;
}

.left-section {
  flex: 1;
  background: linear-gradient(145deg, #409eff 0%, #1a73e8 100%);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.left-content {
  text-align: center;
  color: white;
  position: relative;
  z-index: 2;
}

.overlay-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
  letter-spacing: 1px;
}

.overlay-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
}

.decoration-circle {
  position: absolute;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  bottom: -50px;
  right: -50px;
  z-index: 1;
}

.right-section {
  flex: 1;
  padding: 2rem;
  display: flex;
  align-items: center;
}

.form-wrapper {
  width: 100%;
  max-width: 360px;
  margin: 0 auto;
}

.form-header {
  text-align: center;
  margin-bottom: 2rem;
}

.welcome-text {
  font-size: 1.8rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 0.5rem;
}

.welcome-subtitle {
  color: #7f8c8d;
  font-size: 1rem;
}

.input-style {
  transition: all 0.3s ease;
}

.input-style:focus-within {
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 1rem 0 1.5rem;
}

.custom-checkbox {
  color: #606266;
}

.custom-login-button {
  width: 100%;
  padding: 14px;
  font-size: 1.1rem;
  border-radius: 8px;
  background: linear-gradient(45deg, #409eff, #67c23a);
  border: none;
  transition: all 0.3s ease;
}

.custom-login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.4);
}

.visitor-login-button {
  width: 100%;
  padding: 14px;
  font-size: 1.1rem;
  border-radius: 8px;
  margin: 1rem 0;
  transition: all 0.3s ease;
}

.visitor-login-button:hover {
  background: #e6f0ff;
  transform: translateY(-2px);
}

.register-tip {
  text-align: center;
  color: #606266;
  font-size: 0.9rem;
}

.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
}

.custom-dialog :deep(.el-dialog__footer) {
  text-align: center;
}

.dialog-footer .el-button {
  min-width: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    width: 100%;
    height: auto;
    max-width: 400px;
  }

  .left-section {
    padding: 2rem;
    min-height: 200px;
  }

  .right-section {
    padding: 1.5rem;
  }

  .overlay-title {
    font-size: 2rem;
  }

  .overlay-subtitle {
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .form-wrapper {
    max-width: 100%;
  }

  .welcome-text {
    font-size: 1.5rem;
  }
}
</style>